import React, { useEffect, useState, useContext,useMemo } from 'react'
import axios from 'axios'
import { Navigate, useNavigate, useParams } from 'react-router-dom'
import style from './List.module.scss'
import homeCtx from '../context/Context'
import classNames from 'classnames'

// 列举动态路由参数
const enumList = {
  zh: 'https://zyxcl.xyz/exam_api/zh',
  xl: 'https://zyxcl.xyz/exam_api/xl',
  sx: 'https://zyxcl.xyz/exam_api/sx'
}

const List = () => {
  const params = useParams()
  const [list,setList] = useState([])
  const {sortType,isGrid} = useContext(homeCtx)
  const navigate = useNavigate()

  // console.log(isGrid)
  
  // 监听list和sortType 改变 
  const sortList = useMemo(() => {
    if(sortType === 0) return list
    const newSortList = [...list]
    if(sortType === 1) {
      newSortList.sort((a,b) => a.price - b.price)
    }else {
      newSortList.sort((a,b) => b.price - a.price)
    }
    return newSortList
  },[list,sortType])


  // console.log(params)
  const getList = async () => {
    const res = await axios.get(enumList[params.id])
    // console.log(res.data.items)
    setList(res.data.items)
  }
  //  监听某一个变量改变
  useEffect(() => {
    getList()
  },[params.id])
  

  
  // 如果在枚举列表内没找到对应的参数  跳转404
  if(!enumList[params.id]) return <Navigate to='/404'/>


  return (
    <div className={classNames(style.list,{[style.grid]:isGrid})}>
      {sortList.map(item => 
        <div key={item.item_id} className={style.listItem} onClick={() => 
          navigate(`/detail?id=${item.item_id}`)
        }>
          <img src={item.img} alt="" />
          <div className={style.con}>
            <span>{item.title}</span>
            <p>价格:{item.price}</p>
          </div>
        </div>
      )}
    </div>
  )
}

export default List